package com.itheima.tlias84.controller;

import com.itheima.tlias84.Po.InsertEmpParam;
import com.itheima.tlias84.Po.SelectEmpPageParam;
import com.itheima.tlias84.Po.UpdateEmpParam;
import com.itheima.tlias84.Service.EmpService;
import com.itheima.tlias84.Util.ResultUtil;
import com.itheima.tlias84.dto.SelectEmpDTO;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/emps")
@CrossOrigin
public class EmpController {
    @Resource
    EmpService empService;

    @GetMapping
    public ResultUtil selectEmpByPage(SelectEmpPageParam param) {
        if (Objects.isNull(param.getPage()) || Objects.isNull(param.getPageSize())) {
            return ResultUtil.fail("参数错误");
        }
        //      List<SelectEmpDTO> dtos = empService.selectEmpByPage(param);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("total",dtos.size());
//        map.put("rows",dtos);
        return empService.selectEmpByPage(param);
    }

    @DeleteMapping
    public ResultUtil batchDelete(@RequestParam("ids") List<Integer> ids) {
        if (ids.isEmpty()) {
            return ResultUtil.fail("请先选择id");
        }
        int flag = empService.batchDelete(ids);
        return ResultUtil.success(flag);

    }

    @PostMapping
    public ResultUtil insertEmp(@Validated @RequestBody InsertEmpParam param) {
        int i = empService.insertEmp(param);
        return i == 0 ? ResultUtil.fail("新增失败") : ResultUtil.success("新增成功");
    }

    @GetMapping("/{id}")
    public ResultUtil selectEmpById(@PathVariable("id") Integer id) {
        SelectEmpDTO dto = empService.selectEmpById(id);
        return ResultUtil.success(dto);
    }

    @PutMapping
    public ResultUtil updateEmp(@RequestBody UpdateEmpParam param) {
        int i = empService.updateEmp(param);
        return i == 0 ? ResultUtil.fail("修改失败") : ResultUtil.success("修改成功");
    }

    @GetMapping("/list")
    public ResultUtil selectEmpByPage() {
        List<SelectEmpDTO> dtos = empService.selectAll();
        return ResultUtil.success(dtos);

    }


}
